<?php
namespace Admin\Controller;
use Think\Controller;
/*
 ×商品管理控制器
 ×
 */
 class ItemController extends AdminController {
 public function index()
 	{
 		$arg['page']=I('get.page',1,'strip_tags');
 		$item=D('Item');
 		$result=$item->index($arg['page']);
 		  /*顶级类目**/
        $toptype=M('type')->where("pid=0")->getField("typeid,typename");
       $this->assign('toptype',$toptype);
 		
 		$this->assign('items',$result['item']);
 		$this->assign('pagearr',$result['pagearr']);
 		$this->assign('yid',$_SESSION['yid']);
 		$this->display('index');
 	}
	/*
	 *添加商品
	 */
	public function addItem()
	{
		$typeid=I('get.typeid','','strip_tags');
		//获取所有类目
		$type=new \Admin\Controller\TypeController();
		$typearr=$type->getListCat();
		 /*顶级类目**/
        $toptype=M('type')->where("pid=0")->getField("typeid,typename");
       $this->assign('toptype',$toptype);

		//如果typeid非空需要选择商品属性
		if(!empty($typeid))
		{
		
			//获取所有的品牌
			$brands=M('brand')->getField('brandname',true);
			$temp_brand=array();
			foreach ($brands  as $key => $value) {
				$temp_brand[$key]['label']=$value;
				$temp_brand[$key]['value']=$value;
			}

		 //获取总后台下所有供货商
		/// $suppliers=M('supper_user')->where('adminid !=0 ')->getField('supperid,name');
			$suppliers=M('supper_user')->where("yid='%s'",$_SESSION['yid'])->getField('supperid,contactname');

		//获取该类目下的所有属性
			$typeproperty=M('type a')->join('inner join '. C('DB_PREFIX').'type_property b on a.typeid=b.typeid ')
			->where('a.typeid=%d',$typeid)
			->getField('b.propertyid,a.typeid,a.typename,b.propertyname');

			if(!empty($typeproperty))
			{
				foreach($typeproperty as $key=>&$value)
				{
					$where['propertyid']=$key;
					$value['select']=M('type_property a')->join('inner join '.C('DB_PREFIX').'type_propertyvalue b on a.propertyid=b.propertyid')
					->where('a.propertyid=%d',$where['propertyid'])
					->getField('b.valueid,a.propertyid,a.propertyname,b.propertyvalue ');
				}

			}
		
		

		 
		 $this->assign('suppliers',$suppliers);
		 $this->assign('typearr',$typearr);//分类树
		 $this->assign('typeproperty',$typeproperty);
		 $this->assign('brands',json_encode($temp_brand,JSON_UNESCAPED_UNICODE));
		 

		 $this->assign('typeid',$typeid);
		 $this->display('pro_spec');

		}else{

			$this->assign('typearr',$typearr);//分类树
			$this->display();
		}

	}
	//保存商品
	public function saveItem()
	{
	//获取商品基本 信息
	$data['areatype']=!empty($_POST['areatype'])?$_POST['areatype']:0;/////购买区域
	$data['status']=2;///新添加的产品默认是下架
	$data['itemname']=I('post.itemname','','strip_tags');
	$data['bn']=I('post.bn','','strip_tags');
	$data['price']=!empty($_POST['price'])?$_POST['price']:0;
	$data['supperprice']=!empty($_POST['supperprice'])?$_POST['supperprice']:0;
	$data['supperid']=I('post.supperid',0,'strip_tags');//供货商ID
	$data['yid']=!empty($_SESSION['yid'])?$_SESSION['yid']:0;//运营商id
	$data['inventory']=!empty($_POST['inventory'])?$_POST['inventory']:0;
	$data['typeid']=I('post.itemtype','','strip_tags');
	$data['createtime']=time();
	$data['examine']=0;////刚添加的商品默认没有审核


	//判断是否存在新增品牌
	$brandname=I('post.brand','','strip_tags');

	//检测数据库是否存在这个品牌，不存即添加
	$brand_id=M('brand')->where("brandname='%s'",$brandname)->getField('brandid');

	if (is_null($brand_id))
	{
		//将新增品牌插入brand 表，将type与 brand 关联起来 type_brand 表
		$brand=M('brand');
		$type_brand=M('type_brand');
		$brand->startTrans(); //开启事务
		$brand->create();
		$brand->brandname=$brandname;
		$brand->createtime=time();
		$new_bid= $brand->add();
		$type_brand->create();
	   $re=M('type_brand')->where("typeid='%d' and brandid='%d'",$_POST['itemtype'],$brand_id)->find();
	   if(is_null($re)){
		$type_brand->typeid=$data['typeid'];
		$type_brand->brandid=$new_bid;
		$re_val=$type_brand->add("");
		if(!empty($new_bid) && !empty($re_val))
		{
			$brand->commit(); //成功则提交
			$data['brandid']=$new_bid;
		}else{
			$brand->rollback();// 失败回滚
		}
		} //插入成功返回值
		
	}else{
		$data['brandid']=$brand_id;
	}

	$itemdescdata=!empty($_POST['editorValue'])?$_POST['editorValue']:'';
	//获取商品属性数组
	$property=I('post.proper','','strip_tags');
	//货品颜色
	$p_color=I('post.p_color','','strip_tags');
	//货品库存
	$p_inventory=I('post.p_inventory',0,'strip_tags');
	//货品价格
	$p_price=I('post.p_price',0,'strip_tags');
	$p_supprice=I('post.supper_price',0,'strip_tags');

    //调用上传图片
	if(!empty($_FILES['listimg']['tmp_name'])){
		$data['itemimg']=$this->uploadimg();

		if ($data['itemimg']==false)
		{
			$this->error('图片尺寸不符');
	     	//echo  "<script type='text/javascript'>alert('图片尺寸不符');window.history.go(-1);</script>";die;
		}
	}

	$item=M('item');
	//添加商品基本信息
	$itemid=$item->data($data)->add();
	if (!empty($itemid)) {
		$itemdesc=M('item_desc');
		$itemdesc->create();
		$itemdesc->itemid=$itemid;
		$itemdesc->itemdesc=$itemdescdata;
		$itemdesc->add();
	}
	//保存产品属性
	if(!empty($itemid)){

		if(!empty($property))
		{
			$item_property=M('item_property');
			$datalist=array();
			foreach($property as $key=>$value)
			{
				$datalist[]=array('itemid'=>$itemid,'propertyid'=>$key,'propertyvalueid'=>$value);
			}
		//批量保存商品属性
			$item_property->addAll($datalist);
		}
		//保存商品的颜色，库存，价格,供货价格
		$temp_product=array();

		if(!empty($p_price) && !empty($p_color) && !empty($p_inventory) &&!empty($p_supprice))
		{
			$product=M('product');
			$product->create();
			foreach ($p_price as $key => $value)
			{
				$product->itemid=$itemid;
				$product->inventory=$p_inventory[$key];
				$product->price=$p_price[$key];
				$product->color=$p_color[$key];
				$product->supprice=$p_supprice[$key];
				$result=$product->add();
			}
		}
	}

	if($itemid || $result)
	{
		//echo "<script type='text/javascript'>alert('添加商品成功');</script>";
		$this->success('添加产品成功');
	}else
	{
		$this->error('添加产品失败，请重新添加');
	}

	}
	

	/*
	 *编辑产品
	 *@param  itemid
	 */
	public function editItem(){
		$itemid=I('get.itemid','','strip_tags');
		if(!$itemid) return false;
      //获取分类树
		$type=new \Admin\Controller\TypeController();
		$typearr=$type->getListCat();
      //获取商品基本信息
		$item=M('item');
		$iteminfo=$item->where('itemid=%d',$itemid)->select();
		//获取所有品牌
		$brands=M('brand')->getField('brandid,brandname');
		 //获取该运营商下所有供货商
		 $yid=!empty($_SESSION['yid'])?$_SESSION['yid']:0;
		 $suppliers=M('supper_user')->where('yid=%d',$yid)->getField('supperid,contactname');
		 //如果此商品存在颜色规格
		$products=array();
		$product=M('product');
		$productids=$product->where('itemid=%d',$itemid)->getField('productid',true);
		if(!empty($productids))
		{
			foreach($productids as $key=>$value)
			{
				$products[]=$product->where('productid=%d',$value)->getField('productid,inventory,price,color,supprice');
			}

		}

	  //获取商品详情
		$detail=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');

      //获取该类目下的所有属性
		$typeproperty=M('type a')->join('inner join '. C('DB_PREFIX').'type_property b on a.typeid=b.typeid ')
		->where('a.typeid=%d',$iteminfo[0]['typeid'])
		->getField('b.propertyid,a.typeid,a.typename,b.propertyname');
		if(!empty($typeproperty))
		{
			foreach($typeproperty as $key=>&$value)
			{
				$where['propertyid']=$key;
				$value['select']=M('type_property a')->join('inner join '.C('DB_PREFIX').'type_propertyvalue b on a.propertyid=b.propertyid')
				->where('a.propertyid=%d',$where['propertyid'])
				->getField('b.valueid,a.propertyid,a.propertyname,b.propertyvalue ');
			}

		}
		//获取已选择的属性
		$seledpro=M('item_property')->where('itemid=%d',$iteminfo[0]['itemid'])->getField('propertyid,propertyvalueid');
		foreach($typeproperty as $key=>&$value)
		{

			foreach($value['select'] as $k=>&$v)
			{

				if($v['valueid']==$seledpro[$key])
				{

					$v['selected']='true';
				}
			}
		}
		////获取该商品的购买区
		$areatype=M('item')->where("itemid='%d'",$itemid)->getField("areatype");
		
		////获取运营商下所有的购买区
//var_dump($areatype);
		$this->assign("areatype",$areatype);
		$this->assign('suppliers',$suppliers);
		$this->assign('detail',$detail);
		$this->assign('typearr',$typearr);
		$this->assign('products',$products);
		$this->assign('iteminfo',$iteminfo[0]);
		$this->assign('brands',$brands);
		$this->assign('typeproperty',$typeproperty);
		$this->display('edititem');
	}


	//更新产品
	public function updateItem()
	{

		/*$data['activityid']=$_POST['activityid'];////活动
		$data['discount']=$_POST['discount'];*////商品折扣
		$data['modifietime']=time();
		$itemid=I('post.itemid','','strip_tags');
		$data['typeid']=I('post.typeid','','strip_tags');
		$data['itemname']=I('post.itemname','','strip_tags');
		$data['bn']=I('post.bn','','strip_tags');
		$data['brandid']=I('post.brand','','strip_tags');
		$data['price']=I('post.price','','strip_tags');
		$data['mkprice']=I('post.mkprice','','strip_tags');
		$data['inventory']=I('post.inventory','','strip_tags');
		$data['supperprice']=I('post.supperprice',0,'strip_tags'); //供货价
		$data['supperid']=I('post.supperid',0,'strip_tags');
		$data['yid']=!empty($_SESSION['yid'])?$_SESSION['yid']:0;//运营商id
        $data['examine']=0;////跟新的产品默认没有审核
       $data['status']=2;//更新的产品默认是下架
       $data['areatype']=!empty($_POST['areatype'])?$_POST['areatype']:0;////购买区域

         
         //检测数据库是否存在这个品牌，不存即添加
	$brand_id=M('type_brand')->where("brandid='%d' and typeid='%d'",$_POST['brand'],$_POST['typeid'])->find();
	if (is_null($brand_id))
	{
		$da['typeid']=I('post.typeid','','strip_tags');
		$da['brandid']=I('post.brand','','strip_tags');
		$re=M('type_brand')->add($da);

	}

		 //商品详情
		$detail['itemdesc']=$_POST['editorValue'];
		$typeid=I('post.itemtype','','strip_tags');
		$proper=I('post.proper','','strip_tags');
		 //调用上传图片

		if(!empty($_FILES['listimg']['tmp_name']))
		{
			$data['itemimg']=$this->uploadimg();

			if ($data['itemimg']==false)
			{
				$this->error('图片尺寸不符');
			     	//echo  "<script type='text/javascript'>alert('图片尺寸不符');window.history.go(-1);</script>";die;
			}
		}
		 	//更新基本信息
		$item=M('item');

		$result=$item->where('itemid=%d',$itemid)->save($data);


	        //更新商品详情
		$ret=M('item_desc')->where('itemid=%d',$itemid)->getField('itemid');
		if(!$ret){
			$detail['itemid']=$itemid;
			M('item_desc')->add($detail);
		}else{

			M('item_desc')->where('itemid=%d',$itemid)->save($detail);
		}
		 	//更新属性
		$item_property=M('item_property');

		foreach($proper as $key=>$value)
		{
			$map['propertyvalueid']=$value;
			$tempres=$item_property->where('itemid=%d and propertyid=%d',$itemid,$key)->count();
			if(!empty($tempres)){
				$result=$item_property->where('itemid=%d and propertyid=%d',$itemid,$key)->save($map);
			}else{
				$map['itemid']=$itemid;
				$map['propertyid']=$key;
				$result=$item_property->add($map);
			}

		}
		 	//组合颜色、库存、价格
		$p_color=I('post.p_color','','strip_tags');
		$p_price=I('post.p_price',0,'strip_tags');
		$p_inventory=I('post.p_inventory',0,'strip_tags');
		$p_supprice=I('post.p_supprice',0,'strip_tags');

		if(!empty($p_color) && !empty($p_price) &&!empty($p_inventory) && !empty($p_supprice) )
		{
			$products=array();
			$i=0;
			foreach($p_price as $key=>$value)
			{
				$products[$i]['price']=$value;
				$products[$i]['color']=$p_color[$key];
				$products[$i]['inventory']=$p_inventory[$key];
				$products[$i]['supprice']=$p_supprice[$key];
				$products[$i]['productid']=$key;
				$i+=1;
			}
		 		//修改颜色、库存、价格
			$product=M('product');
			foreach($products as $key=>$value)
			{
				$product->itemid=$itemid;
				$product->inventory=$value['inventory'];
				$product->price=$value['price'];
				$product->color=$value['color'];
				$product->supprice=$value['supprice'];
				$temp_res=$product->where('productid=%d',$value['productid'])->save();

			}
		}

	        //判断是否新增颜色，库存，价格
		$n_color=I('post.n_color','','strip_tags');
		$n_price=I('post.n_price',0,'strip_tags');
		$n_inventory=I('post.n_inventory',0,'strip_tags');
		$n_supprice=I('post.n_supprice',0,'strip_tags');
		if(!empty($n_price) && !empty($n_color) && !empty($n_inventory) && !empty($n_supprice))
		{
			$product=M('product');
			$product->create();
			foreach ($n_price as $key => $value)
			{
				$product->itemid=$itemid;
				$product->inventory=$n_inventory[$key];
				$product->price=$n_price[$key];
				$product->color=$n_color[$key];
				$product->supprice=$n_supprice[$key];
				$result=$product->add();

			}
		}
		 //更新成功
		 $ipage=cookie('page');
		 $ipage=!empty($ipage)?$ipage:1;
		 $this->redirect('item/index', array('page' =>$ipage), 0.001,"<script>alert('修改成功')</script>");
		

	}
	/*
       * 删除商品
       *@param itemid 商品id
	 */
	public function delItem()
	{

		$itemid=I('get.itemid',0,'strip_tags');

		if (empty($itemid)) {
			echo  json_encode(array("status"=>0,"msg"=>"参数错误" ),JSON_UNESCAPED_UNICODE);
			return '';
		}

		$result=M('item')->where("itemid=%d",$itemid)->delete();

		if (!empty($result))
		{
			$item_desc=M('item_desc');
			$item_property=M('item_property');
			$product=M('product');
			$temres=$item_desc->where("itemid=%d",$itemid)->count();

			if(!empty($temres)) $item_desc->where("itemid=%d",$itemid)->delete();

			$temres=$item_property->where("itemid=%d",$itemid)->count();

			if(!empty($temres))   $item_property->where("itemid=%d",$itemid)->delete();

			$temres=$product->where("itemid=%d",$itemid)->count();

			if (!empty($temres))
			{
				$product->where("itemid=%d",$itemid)->delete();
			}

			echo json_encode(array("status"=>1,"msg"=>"删除成功"),JSON_UNESCAPED_UNICODE) ;

		}else
		{
			echo json_encode(array("status"=>0,"msg"=>"删除失败"),JSON_UNESCAPED_UNICODE) ;
		}



	}

	//公共方法
	public function cstrpos($haystack,$needle)
	{

		return strpos(strval($haystack),strval($needle)) !== false;

	}
//上传图片
	public function uploadimg(){
			//保存商品图片
		$config['path']=C('Admin_IMG_PATH');
		$config['maxwidth']=C('LIST_MAX_WIDTH');
		$config['maxheight']=C('LIST_MAX_HEIGHT');
		 //判断是那个供应商上传的，重新定义图片路径
		if(!file_exists($config['path']))
		{
			mkdir( $config['path'], 0777 , true );

		}
		$config['maxsize']=C('IMG_MAX_SIZE');
		$img=imgUpload($config);
		 //上传出错
		if(is_string($img)){
			return false;
		}
		$imginfo=$img['listimg'];
		if(!empty($imginfo['savename']))
		{
			$itemimg=substr(C('Admin_IMG_PATH'),1).$imginfo['savepath'].$imginfo['savename'];

		}

		return $itemimg;
	}
	

	/*
	 *商品预览
	 *@param Itemid 
	 *
	 */
	public function viewItem()
	{
		$itemid=I('get.itemid',0,'strip_tags');
		$result=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');
		$this->assign('itemdesc',$result);
		$this->display('preview');
	}


	/**
	 * 商品上架
	 */
	public  function upshelves(){
		$where['itemid']=$_GET['itemid'];
        $data['status']=1;
        $examine=M('item')->where($where)->getField('examine');
        
        if(empty($examine)){
        	echo '3';///产品未上架
        	return '';
        	
        }
		$res=M('item')->where($where)->save($data);
		if($res===false)
		{
			echo '1';//产品上架成功
		}else
		{
        echo '2';///产品上架失败;
		}



	}
	/**
	 * 商品下架
	 */
	public function down(){
		$where['itemid']=$_GET['itemid'];
		$map['status']=2;
		$re=M('item')->where($where)->save($map);
		if($re===false){
			echo '2';///产品下架失败

		}else{
			echo '3';///商品下架成功
		}


	}



	/*
	 *类目、品牌 通过ajax 联动
	 */
	public function getBrand()
	{
		$typeid=I('get.typeid',0,'strip_tags');
		$brandid=!empty($_COOKIE['brandid'])?$_COOKIE['brandid']:0;
		//获取所有品牌
		$brands=M('brand a')->join('inner join '.C(DB_PREFIX).'type_brand b on a.brandid=b.brandid')
		        ->where('b.typeid=%d',$typeid)->order('a.brandid desc')->getField('a.brandid,a.brandname');
		$bsting="<option value=0>选择品牌</option>";
		foreach ($brands as $key => $value)
		 {
			if ($key==$brandid)
			{
				$bsting.='<option value='.$key.' selected >'.$value.'</option>';
			}else
			{
				$bsting.='<option value='.$key.' >'.$value.'</option>';
			}
		}
		echo json_encode($bsting,JSON_UNESCAPED_UNICODE);
	}

	/*
	 * ajax 筛选商品
	 * @param 
	 * echo json
	 */
	public function getItem(){
		$arg=array();
		$arg['typeid']=I('post.typeid',0,'strip_tags');
		$arg['brandid']=I('post.brandid',0,'strip_tags');
		$arg['keywords']=I('post.keywords','','strip_tags');
		$arg['page']=I('post.page',1,'strip_tags');
		$arg['yid']=I('post.yid','','strip_tags');
		$arg['ally']=I('post.ally','','strip_tags');
        $arg['platid']=I('post.platid','','strip_tags');
		$item=D('item');
		$result=$item->index($arg);
		

		if(!empty($result['item'])){
			$result['status']=1;
			$result['item']=array_values($result['item']);
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
			return '';

		}

		$result['status']=0;
		$result['message']='暂无数据';
		echo  json_encode($result,JSON_UNESCAPED_UNICODE);
	}
//
	/*
	 *ajax 检测商品Bn 是否唯一
	 *retun json
	 */
		public function ajaxBn(){
			$bn=I('get.bn','测试','strip_tags');
			$result=M('item')->where("bn='%s'",$bn)->count();
			if(!empty($result)){
				echo json_encode(array('msg'=>'型号已添加','status'=>0),JSON_UNESCAPED_UNICODE);
			}else{
				echo json_encode(array('msg'=>'ok','status'=>1),JSON_UNESCAPED_UNICODE);
			}
			
			
	}

	//ajax  获取商品首页 类目、品牌、 是否上下架
	public function Type2Brand(){
		$typeid=!empty($_COOKIE['typeid'])?$_COOKIE['typeid']:0;
		$brandid=!empty($_COOKIE['brandid'])?$_COOKIE['brandid']:0;

		//获取所有类目
		$type=new \Admin\Controller\TypeController();
		$typearr=$type->getListCat();
		//获取所有品牌
		$brands=M('brand')->order('brandid desc')->getField('brandid,brandname');
		$string="";
		foreach ($typearr as $key => $value)
		{
			if($typeid ==$key)
			{
				$string.='<option value='.$key.' selected >'.str_repeat('&nbsp;&nbsp;&nbsp;',$value['level']).$value['typename'].'</option>';
			}else
			{
				$string.='<option value='.$key.' >'.str_repeat('&nbsp;&nbsp;&nbsp;',$value['level']).$value['typename'].'</option>';
			}
		}
		

		$bsting='';
		foreach ($brands as $key => $value)
		 {
			if ($key==$brandid)
			{
				$bsting.='<option value='.$key.' selected >'.$value.'</option>';
			}else
			{
				$bsting.='<option value='.$key.' >'.$value.'</option>';
			}
		}
		$result['string']=$string;
		$result['bsting']=$bsting;
		echo json_encode($result,JSON_UNESCAPED_UNICODE);

	}
	 /**
      * 获取二级类目
      */
     public function stype(){
        $where['pid']=$_GET['typeid'];
       $setype=M('type')->where($where)->getField('typeid,typename');
       $str='';
   foreach($setype as  $k=>$v){
    $str.= '<option value='.$k.'>'.$v.'</option>';

   }
  echo $str;
       


     }
     /**
      * 获取品牌
      */
     public function brand(){
    $where['a.typeid']=$_GET['brandid'];
    $brands=M('type_brand a')
    ->join('cart_brand b on a.brandid=b.brandid')
    ->where($where)
    ->getField('b.brandid,b.brandname');
   foreach ($brands as $k=>$v){
    $str.= '<option value='.$k.'>'.$v.'</option>';
   }
   echo $str;
     }


/**
     * 检测品牌是否存在
     */
    public function ajaxbrand(){
        $where['brandname']=I('get.brand','','strip_tags');
        $id=M('brand')->where($where)->getField("brandid");
        if(empty($id))
        {
            $data = array('status'=>404,'code'=>'error','info'=>'该品牌不存在请先添加');
            echo json_encode($data);
        }else
        {
           $data = array('status'=>200,'code'=>'success','info'=>'允许添加');
           echo json_encode($data);

       }
   }


	

}